package com.lzj.service;


import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.lzj.lock.Lock;
import com.lzj.mapper.TradeMapper;
import com.lzj.vo.Stock;

@Service
public class TradeService {
	
	private static final Logger logger = LoggerFactory.getLogger(TradeService.class);
	
	//JUC提供锁
	private ReentrantLock reentrantLock = new ReentrantLock();
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	//自己实现的锁
	private Lock lock = new Lock();

	@Autowired
	private TradeMapper tradeMapper;
	
	public Stock select(int id) {
		return tradeMapper.select(id);
	}
	
	public void update(int id) {
		Stock stock = tradeMapper.select(id);
		tradeMapper.update(stock);
	}
	
	/**
	 * 减库存
	 */
	public String decStockNoLock() {
		lock.lock();
		Integer stock = null;
		List<Map<String, Object>> result = jdbcTemplate.queryForList("select stock from t_stock where id=1");
		if(result == null ||
				(stock = (Integer) result.get(0).get("stock"))<=0) {
			logger.info("下单失败，已经没有库存！");
			lock.unlock();
			return "下单失败，已没有库存";
		}
		stock--;
		jdbcTemplate.update("update t_stock set stock=? where id=1",stock);
		logger.info("下单成功，当前剩余产品数 -------------------->"+stock);
		lock.unlock();
		return "下单成功，当前剩余产品数： ------------->"+stock;
	}
	
}
